package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService orderService;
    
    @Autowired
    private JedisPool jedisPool;


    //添加预约
    
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        
        //1.获取用户输入的手机号
        String telephone = (String) map.get("telephone");
        //2.获取保存在redis中的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");

        //3.进行判断
        if (validateCodeInRedis != null && validateCode != null && validateCodeInRedis.equals(validateCode)){
            //比对成功,调用service中的方法进行处理
            map.put("orderType", Order.ORDERTYPE_WEIXIN);//明确预约的方式
            Result result = null;
            try {
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                if (null==result){
                    result = new Result(false,MessageConstant.ORDER_FAIL);
                }
                return result;
            }
            if (result.isFlag()){//预约成功,给用户发送短信

                try {
                    SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone, (String) map.get("orderDate"));

                    System.out.println("[已预约成功] + 手机号是:" + telephone + "预约的时间是" + (String)map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }

            return result;

        }else {//比对不成功

           return new Result(false, MessageConstant.VALIDATECODE_ERROR) ;
        }

    }


    //查看预约详情
    @RequestMapping("findById")
    public Result findById(Integer id){

        try {
          Map map = orderService.findById(id);

          return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();

            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
